<?php
/**
 * Description of articles
 *
 * @author Dmitry
 */
class Models_Articles extends Access_Db {
  function getArticle($id)
  {
    $select = array(
        'id',
        'title',
        'body',
        'created',
        'modified',
        'comments',
        'user_id',
        $this->lang . '_menu_id'
    );
    $table = $this->lang . '_articles';
    $this->select($select, $table, "id='$id' and visible=1");
    $result = $this->getSelected();
    return $result;
  }
  
  function getAllArticles($page = null)
  {
    $select = array(
        'id',
        'title',
        'body',
        'created',
        'modified',
        'comments',
        'user_id',
        $this->lang . '_menu_id'
    );
    $table = $this->lang . '_articles';
    $this->select($select, $table, "visible=1");
    $result = array();
    while($row = $this->getSelected())
    {
      $result[] = $row;
    }
    return $result;
  }
  
  function getAllSubArticles($id)
  {
     $select = array(
         'id',
         'title',
         'modified',
         $this->lang . '_article_id'
     );
     $table = $this->lang . '_sub_articles';
     $where = $this->lang . '_article_id=\'' . $id . '\'';
     $this->select($select, $table, $where);
     $result = array();
     while($row = $this->getSelected())
     {
         $result[] = $row;
     }
     return $result;
  }
  
  function getSubArticle($id)
  {
      $select = array(
        'id',
        'title',
        'body',
        'created',
        'modified',
        'user_id',
        $this->lang . '_article_id'
    );
    $table = $this->lang . '_sub_articles';
    $this->select($select, $table, "id='$id' and visible=1");
    $result = $this->getSelected();
    return $result;
  }

  function getAllComments($id)
  {
      $select = array(
          'id',
          'title',
          'body',
          'created',
          'modified',
          'user_id',
          'article_id',
          'comments_id'
      );
      $table = $this->lang . '_comments';
      $where = "visible='1' and checked='1' and comments_id='0' and article_id='$id' order by created asc ";
      $this->select($select, $table, $where);
      $result = array();
      while($row = $this->getSelected())
      {
          $result[] = $row;
      }
      return $result;
  }
  
  function getArticleId($id)
  {
      $select = array(
          $this->lang . '_article_id'
      );
      $table = $this->lang . '_sub_articles';
      $where = "id='$id'";
      $this->select($select, $table, $where);
      return $this->getSelected();
  }

  function setArticle($arr)
  {
      $query = "INSERT INTO " . $this->lang . "_articles (title, body, " . $this->lang . "_menu_id, visible, comments, news, user_id)
                VALUES (?,?,?,?,?,?,?)";
      $this->prepare($query);
      $this->insert($arr);
      $articleId = $this->getLAstInsertedID();
      $id = $this->getLAstInsertedID();
      $query = "UPDATE " . $this->lang . "_articles SET created=NOW(), modified=NOW() WHERE id='$id'";
      $this->execQuery($query);
      $select = array('max(position)');
      $from = $this->lang . '_menu';
      $this->select($select, $from);
      $maxPosition = $this->getSelected();
      $maxPosition = $maxPosition['max(position)']+1;
      $query = "INSERT INTO " . $this->lang . "_menu (name," . $this->lang . "_menu_id, visible, " . $this->lang . "_article_id, position) VALUES (?,?,?,?,?)";
      $this->prepare($query);
      $menuArr = array(
          $arr['0'],
          $arr['2'],
          $arr['3'],
          $id,
          $maxPosition
      );
      $this->insert($menuArr);
      $query = "INSERT INTO role_permissions (role_id, article_id, action, controller) VALUES (?,?,?,?)";
      $roleId = $this->getSpecialUserGroup($_COOKIE['user_id']);
      $permissionArr = array(
          $roleId['role_id'],
          $articleId,
          'edit',
          'articles'
      );
      $permissionArr1 = array(
          $roleId['role_id'],
          $articleId,
          'remove',
          'articles'
      );
      $permissionArr2 = array(
          $roleId['role_id'],
          $articleId,
          'editing',
          'articles'
      );
      $permissionArr3 = array(
          $roleId['role_id'],
          $articleId,
          'removing',
          'articles'
      );
      $permissionArr4 = array(
          '2',                  //!!!!!!!!! 2 - is a user group (only users can add comment)
          $articleId,
          'add',
          'comment'
      );
      $permissionArr5 = array(
          '2',             //!!!!!!!!! 2 - is a user group (only users can add comment)
          '0',
          'adding',
          'comment'
      );
      $permissionArr6 = array(
          $roleId['role_id'],
          $articleId,
          'addtagto',
          'articles'
      );
      $permissionArr7 = array(
          $roleId['role_id'],
          $articleId,
          'permission',
          'articles'
      );
      $this->prepare($query);
      $this->insert($permissionArr);
      $this->insert($permissionArr1);
      $this->insert($permissionArr2);
      $this->insert($permissionArr3);
      $this->insert($permissionArr4);
      $this->insert($permissionArr5);
      $this->insert($permissionArr6);
      $this->insert($permissionArr7);
  }
  
  function editArticle($arr, $id)
  {
      $query = "UPDATE " . $this->lang . "_articles SET title='"
              . $arr['0'] . "', body='"
              . $arr['1'] . "', " . $this->lang . "_menu_id='"
              . $arr['2'] . "', visible='"
              . $arr['3'] . "', comments='"
              . $arr['4'] . "', news='"
              . $arr['5'] . "', modified=NOW() WHERE id='" . $id . "'";
      $this->execQuery($query);
      $query = "UPDATE " . $this->lang . "_menu SET name='"
              . $arr['0'] . "', visible='"
              . $arr['3'] . "', " . $this->lang . "_menu_id='"
              . $arr['2'] . "' WHERE " . $this->lang . "_article_id='$id'";
      $this->execQuery($query);
  }

  function validateArticle($arr)
  {
      $errors = array();
      if((strlen($arr['0']) > 50) or (strlen($arr['0']) < 1))
      {
        $errors[] = 'Name must be at least 1 and up to 50 characters.';
      }
      if((strlen($arr['1']) < 10))
      {
        $errors[] = 'Content is empty.';
      }
      if(count($errors) > 0)
      {
          return $errors;
      }
      return FALSE;
  }
  
  function validateSubArticle($arr) //comment
  {
      $errors = array();
      if((strlen($arr['0']) > 32) or (strlen($arr['0']) < 1))
      {
        $errors[] = 'Name must be at least 1 and up to 32 characters.';
      }
      if((strlen($arr['1']) < 10))
      {
        $errors[] = 'Content is empty.';
      }
      if(count($errors) > 0)
      {
          return $errors;
      }
      return FALSE;
  }

  function setSubArticle($arr) //add sub article
  {
      $query = "INSERT INTO " . $this->lang . "_sub_articles (title, body, " . $this->lang . "_article_id, visible, comment, user_id)
                VALUES (?,?,?,?,?,?)";
      $this->prepare($query);
      $this->insert($arr);
      $id = $this->getLAstInsertedID();
      $query = "UPDATE " . $this->lang . "_sub_articles SET created=NOW(), modified=NOW() WHERE id='$id'";
      $this->execQuery($query);
      $query = "INSERT INTO role_permissions (role_id, article_id, action, controller) VALUES (?,?,?,?)";
      $roleId = $this->getSpecialUserGroup($_COOKIE['user_id']);
      $permissionArr = array(
          $roleId['role_id'],
          $id,
          'editsub',
          'articles'
      );
      $permissionArr1 = array(
          $roleId['role_id'],
          $id,
          'removesub',
          'articles'
      );
      $permissionArr2 = array(
          $roleId['role_id'],
          $id,
          'editingsub',
          'articles'
      );
      $permissionArr3 = array(
          $roleId['role_id'],
          $id,
          'removing',
          'articles'
      );
      $permissionArr4 = array(
          $roleId['role_id'],
          $id,
          'subpermission',
          'articles'
      );
      $this->prepare($query);
      $this->insert($permissionArr);
      $this->insert($permissionArr1);
      $this->insert($permissionArr2);
      $this->insert($permissionArr3);
      $this->insert($permissionArr4);
  }
  
  function editSubArticle($arr, $id)
  {
      $query = "UPDATE " . $this->lang . "_sub_articles SET title='"
                . $arr['0'] . "', body='"
                . $arr['1'] . "', " . $this->lang . "_article_id='"
                . $arr['2'] . "', visible='"
                . $arr['3'] . "', comment='"
                . $arr['4'] . "', modified=NOW() WHERE id='$id'";
      $this->execQuery($query);
  }

  function searchArticles($word)
  {
      $select = array(
        'id',
        'title',
        'body',
        'created',
        'modified',
        'comments',
        'user_id',
        $this->lang . '_menu_id'
    );
    $table = $this->lang . '_articles';
    $where = '';
    $i = 0;
    foreach ($word as $value)
    {
        $i++;
        $where.= "title LIKE '%$value%' OR body LIKE '%$value%'" . ($i==count($word)?"":" OR ");
    }
    $where.= " AND visible='1' ORDER BY modified ASC";
    $result = array();
    $this->select($select, $table, $where);
    while ($row = $this->getSelected())
    {
        $result[] = $row;
    }
    return $result;
  }
  
  function searchSubArticles($word)
  {
      $select = array(
        'id',
        'title',
        'body',
        'created',
        'modified',
        'user_id',
        $this->lang . '_article_id'
    );
    $table = $this->lang . '_sub_articles';
    $where = '';
    $i = 0;
    foreach ($word as $value)
    {
        $i++;
        $where.= "title LIKE '%$value%' OR body LIKE '%$value%'" . ($i==count($word)?"":" OR ");
    }
    $where.= " AND visible='1' ORDER BY modified ASC";
    $result = array();
    $this->select($select, $table, $where);
    while ($row = $this->getSelected())
    {
        $result[] = $row;
    }
    return $result;
  }

  function cleanPostData($word)
  {
    $word = strip_tags($word);
    $word = strtolower($word);
    $word = preg_replace('~[^a-z0-9 \x80-\xFF]~i', "",$word); 
    return $word;
  }

    function cleanArrayToSearch($minLength, $words = array(), $max = 0)
    {
        $result = array();
        $i = 0;
        foreach($words as $value){
            if(strlen(trim($value)) >= $minLength){
                $i++;
                if($i <= $max){
                    $result[] = trim($value);
                }
            }
        }
        return $result;
    }
  
  function searchValidate($word, $minLength)
  {
      $errors = array();
      if(strlen($word) < $minLength)
      {
          $errors[] = 'Word is very short.';
      } else {
          return FALSE;
      }
      return $errors;
  }

  function countComment($id)
  {
      $select = array('count(id)');
      $table = $this->lang . '_comments';
      $where = "article_id='$id' and checked='1'";
      $this->select($select, $table, $where);
      return $this->getSelected();
  }
  
  function setComment($arr)
  {
      $query = "INSERT INTO " . $this->lang . "_comments (title, body, user_id, article_id) VALUES (?,?,?,?)";
      $this->prepare($query);
      $this->insert($arr);
      $id = $this->getLAstInsertedID();
      $query = "UPDATE " . $this->lang . "_comments SET created=NOW(), modified=NOW() where id='$id'";
      $this->execQuery($query);
      $query = "INSERT INTO role_permissions (role_id, article_id, action, controller) VALUES (?,?,?,?)";
      $roleId = '4'; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 4 - is id of admin role
      $permissionArr = array(
          $roleId,
          $id,
          'commentok',
          'admin'
      );
      $permissionArr1 = array(
          $roleId,
          $id,
          'commentremove',
          'admin'
      );
      $this->prepare($query);
      $this->insert($permissionArr);
      $this->insert($permissionArr1);
  }
  
  function getNewCommentsCount()
  {
      $select = array(
          'count(id)'
      );
      $from = $this->lang . "_comments";
      $where = "checked='0'";
      $this->select($select, $from, $where);
      return $this->getSelected();
  }
  
  function getUserDataComment($id)
  {
      $select = array(
          'id',
          'first_name',
          'second_name'
      );
      $from = 'users_data';
      $where = "user_id='$id'";
      $this->select($select, $from, $where);
      $data = $this->getSelected();
       $select = array(
          'id',
          'login'
      );
      $from = 'users';
      $where = "id='$id'";
      $this->select($select, $from, $where);
      $login = $this->getSelected();
      $data['login'] = $login['login'];
      return $data;;
  }
  
  function getNewComments()
  {
      $select = array(
          'id',
          'title',
          'body',
          'created',
          'user_id',
          'article_id'
      );
      $from = $this->lang . '_comments';
      $where = "checked='0'";
      $this->select($select, $from, $where);
      $result = array();
      while($row = $this->getSelected())
      {
          $result[] = $row;
      }
      return $result;
  }
  
  function getAllCommentsForAdmin()
  {
      $select = array(
          'id',
          'title',
          'body',
          'created',
          'user_id',
          'article_id'
      );
      $from = $this->lang . '_comments';
      $where = "1 order by created desc";
      $this->select($select, $from, $where);
      $result = array();
      while($row = $this->getSelected())
      {
          $result[] = $row;
      }
      return $result;
  }
  
  function setCommentOk($id)
  {
      $query = "UPDATE " . $this->lang . "_comments SET checked='1' WHERE id='$id'";
      $this->execQuery($query);
  }
  
  function deleteComment($id)
  {
      $query = "DELETE FROM " . $this->lang . "_comments WHERE id='$id'";
      $this->execQuery($query);
      $query = "DELETE FROM role_permissions WHERE (action='commentok' OR action='commentremove') AND controller='admin' AND article_id='$id'";
      $this->execQuery($query);
  }
  
  function setMenuHeader($arr) //set title of menu block
    {
        $query = "INSERT INTO $this->lang" . "_menu (name, visible)
                    VALUES (?,?)";
        $this->prepare($query);
        $this->insert($arr);
    }
}